package com.sec.android.app.myfiles.dialog;

import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;

import com.sec.android.app.myfiles.activity.AbsMyFilesActivity;
import com.sec.android.app.myfiles.listener.DialogReceiver;
import com.sec.android.app.myfiles.listener.ListenerMgr;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.navigation.NavigationChangedObserver;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationManager;

/**
 * Created by jw7.jeong on 2015-09-16.
 */

public abstract class AbsDialogFragment extends DialogFragment implements NavigationChangedObserver.NavigationChangedListener {
    private ListenerMgr mListenerMgr;
    protected Context mContext;
    protected NavigationManager mNavigationManager;
    protected int mProcessId;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AbsMyFilesActivity a = (AbsMyFilesActivity) getActivity();
        mContext = a.getBaseContext();
        mListenerMgr = new ListenerMgr();
        mListenerMgr.addListener(new DialogReceiver(mContext, this, ListenerMgr.LifeCycle.CREATE, ListenerMgr.LifeCycle.DESTROY));
        mListenerMgr.notifyCreate();
        mProcessId = a.getProcessId();
        mNavigationManager = NavigationManager.getInstance(mProcessId);
        mNavigationManager.registerNavigationChangedListener(this);
        return _createDialog();
    }

    public void dismissByBroadcast() {
        dismissAllowingStateLoss();
    }

    @Override
    public void dismissAllowingStateLoss() {
        mListenerMgr.notifyDestroy();
        mNavigationManager.unregisterNavigationChangedListener(this);
        try {
            super.dismissAllowingStateLoss();
        } catch (IllegalStateException e) {
            Log.e(this, "IllegalStateException:" + e.toString());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mListenerMgr.notifyResume();
    }

    @Override
    public void onPause() {
        mListenerMgr.notifyPause();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        dismissAllowingStateLoss();
        super.onDestroy();
    }

    protected abstract Dialog _createDialog();

    @Override
    public void onNavigationChanged(NavigationInfo preInfo, NavigationInfo curInfo) {
        dismissAllowingStateLoss();
    }
}